const express = require('express');
const OSS = require('ali-oss');
const path = require('path');
const Joi = require('joi');
const { pool, initializeDatabase } = require('./db');
require('dotenv').config();

const app = express();
app.use(express.json());

// TidB存储版本API
// 服务器启动时初始化数据库
(async () => {
  try {
    await initializeDatabase();
  } catch (error) {
    console.error('初始化数据库失败:', error);
    process.exit(1);
  }
})();


// OSS客户端配置
const client = new OSS({
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET,
});

// 定义输入参数的校验规则
const reviewSchema = Joi.object({
  userId: Joi.number().integer().required(),
  userName: Joi.string().max(255),
  restaurantName: Joi.string().max(255).required(),
  restaurantLocation: Joi.string().max(255),
  dishName: Joi.string().max(255),
  rating: Joi.number().integer().min(1).max(5).required(),
  reviewText: Joi.string(),
  imageKeys: Joi.string()
});

// 提供静态资源服务
app.use(express.static(path.join(__dirname, 'public')));

// 生成上传用的预签名URL
app.get('/api/upload-url', async (req, res) => {
  try {
    const { filename, contentType } = req.query;
    if (!filename || !contentType) {
      return res.status(400).json({ error: '文件名和内容类型是必需的' });
    }

    // 生成唯一文件名
    const key = `uploads/${Date.now()}-${filename}`;
    
    // 生成预签名URL，有效期1小时
    const url = client.signatureUrl(key, {
      method: 'PUT',
      expires: 3600,
      'Content-Type': contentType
    });

    res.json({ 
      uploadUrl: url,
      fileKey: key,
      expiresIn: 3600
    });
  } catch (error) {
    console.error('生成预签名URL失败:', error);
    res.status(500).json({ error: '生成预签名URL失败' });
  }
});

app.post('/api/reviews', async (req, res) => {
  try {
    // 校验输入参数
    const { error } = reviewSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ message: '参数校验失败', error: error.details });
    }
    const {
      userId,
      userName,
      restaurantName,
      restaurantLocation,
      dishName,
      rating,
      reviewText,
      imageKeys
    } = req.body;
    // 插入数据到数据库
    const insertQuery = `
      INSERT INTO reviews (
        user_id, user_name, restaurant_name, restaurant_location, dish_name, rating, review_text, image_keys
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `;
    await pool.query(insertQuery, [
      userId,
      userName,
      restaurantName,
      restaurantLocation,
      dishName,
      rating,
      reviewText,
      imageKeys
    ]);
    res.status(201).json({ message: '评论已成功提交' });
  } catch (error) {
    console.error('评论提交失败:', error);
    res.status(500).json({ message: '评论提交失败' });
  }
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});